package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var applicationLogger = log.GetLogger()

func writeapplicationLoggerLog(funcName, errMsg string, err error) {
	applicationLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "application.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func CreatApplication(c echo.Context) error {
	application := param.Application{}
	err := c.Bind(&application)
	if err != nil {
		writeapplicationLoggerLog("CreatApplication", "param wrong", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	a := model.Application{}
	a.Forumpost_id = application.Id
	a.Recommed_type = application.Type
	userid := context.GetJWTUserOpenid(c)
	a.Recommed_userid = userid

	a, err = model.CreateApplication(a)
	if err != nil {
		writeapplicationLoggerLog("CreatApplication", "CreatApplication", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorApplicationCreat+err.Error()+a.Forumpost_id)
	}

	err = model.ChangeApplication(application.Id)
	if err != nil {
		writeapplicationLoggerLog("CreatApplication", "ChangeForumpostApplication", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, "ChangeForumpostApplication"+err.Error()+a.Forumpost_id)
	}
	return context.RetData(c, "")
}
